import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/ai_painting")
public class AIPainting extends BaseServlet {
//获取paint_id
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        String id = req.getParameter("id");
        if (id == null) {
            throw new ServletException("please input id");
        }

        String prompt = getPrompt(getJDBCConnection(), id);
//	if(prompt!=null){
//	 	throw new ServletException(prompt+"   "+"找到prompt");
//	}

		//获取paint_id
        AIPaintingEngine engine = new AIPaintingEngine();
        String pid = engine.paint(prompt);
        //存入
        updatePrompt(getJDBCConnection(), id, pid);

        PrintWriter out = resp.getWriter();
        out.printf("开始作画, 画作id为: %s,paint_id为：%s", id,pid);
        out.close();
    }

    public String getPrompt(final Connection conn, String id) throws ServletException {
        Statement stmt = null;
        ResultSet rs = null;
        String prompt = "";
        try {
            stmt = conn.createStatement();
            String sql = String.format("SELECT * FROM t_ai_painting WHERE id = %s", id);
            rs = stmt.executeQuery(sql);

            if (rs.next()) {
                do {
                    prompt = rs.getString("prompt");
                } while (rs.next());
            } else {
                throw new ServletException("prompt info not exist"+rs.getString("prompt"));
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                rs.close();
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return prompt;
    }

    public void updatePrompt(final Connection conn, String id, String pid)
            throws ServletException {
        PreparedStatement stmt = null;
        try {
            stmt = conn.prepareStatement("UPDATE t_ai_painting SET paint_id = ? WHERE id = ?");
            stmt.setString(1, pid);
            stmt.setInt(2, Integer.parseInt(id));
            int row = stmt.executeUpdate();
            if (row == 0) {
                throw new ServletException("update error.");
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
